using System.Buffers;
using System.Net;
using System.Net.Sockets;
using System.Net.Sockets.Kcp;

namespace KaiyunNetwork;

public class KcpClient : IKcpCallback
{
    UdpClient client;

    
    public KcpClient(int port, IPEndPoint endPoint)
    {
        client = port == 0 ? new UdpClient() : new UdpClient(port);
        kcp = new SimpleSegManager.Kcp(2001, this);
        this.EndPoint = endPoint;
        BeginRecv();
    }

    public SimpleSegManager.Kcp kcp { get; }
    public IPEndPoint EndPoint { get; set; }

    public void Output(IMemoryOwner<byte> buffer, int avalidLength)
    {
        var s = buffer.Memory.Span.Slice(0, avalidLength).ToArray();
        client.SendAsync(s, s.Length, EndPoint);
        buffer.Dispose();
    }

    public async void SendAsync(byte[] datagram, int bytes)
    {
        kcp.Send(datagram.AsSpan().Slice(0, bytes));
    }

    public async ValueTask<byte[]> ReceiveAsync()
    {
        var (buffer, avalidLength) = kcp.TryRecv();
        while (buffer == null)
        {
            await Task.Delay(10);
            (buffer, avalidLength) = kcp.TryRecv();
        }

        var s = buffer.Memory.Span.Slice(0, avalidLength).ToArray();
        return s;
    }

    private async void BeginRecv()
    {
        var res = await client.ReceiveAsync();
        EndPoint = res.RemoteEndPoint;
        kcp.Input(res.Buffer);
        BeginRecv();
    }
}